package com.aabte.permissionframeworklearn.permission.service;

import com.aabte.permissionframeworklearn.permission.common.RequestHolder;
import com.aabte.permissionframeworklearn.permission.mapper.SysRoleAclMapper;
import com.aabte.permissionframeworklearn.permission.model.SysRoleAcl;
import com.aabte.permissionframeworklearn.permission.util.IpUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author Daniel
 */
@Service
public class SysRoleAclService {

    @Autowired
    private SysRoleAclMapper sysRoleAclMapper;

    @Autowired
    private SysLogService sysLogService;

    public void changeAcl(Long roleId, List<Long> aclIds) {

        // 判断是否有更新
        List<Long> originAclIdList = sysRoleAclMapper.getAclIdListByRoleIdList(Collections.singletonList(roleId));
        if (originAclIdList.size() == aclIds.size()) {
            Set<Long> originAclIdSet = Sets.newHashSet(originAclIdList);
            Set<Long> aclIdSet = Sets.newHashSet(aclIds);
            originAclIdSet.removeAll(aclIdSet);
            if (CollectionUtils.isEmpty(originAclIdSet)) {
                return;
            }
        }
        updateRoleAcl(roleId, aclIds);
        sysLogService.saveRoleAclLog(roleId, originAclIdList, aclIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateRoleAcl(Long roleId, List<Long> aclIdList) {
        sysRoleAclMapper.deleteByRoleId(roleId);

        if (CollectionUtils.isEmpty(aclIdList)) {
            return;
        }

        List<SysRoleAcl> roleAcls = Lists.newArrayList();
        for (Long aclId : aclIdList) {
            SysRoleAcl sysRoleAcl = SysRoleAcl.builder()
                    .roleId(roleId)
                    .aclId(aclId)
                    .operator(RequestHolder.getCurrentUser().getUsername())
                    .operateIp(IpUtil.getRemoteIpAddress(RequestHolder.getCurrentRequest()))
                    .operateTime(new Date())
                    .build();
            roleAcls.add(sysRoleAcl);
        }
        sysRoleAclMapper.batchInsert(roleAcls);
    }

}
